package org.com.ashen.service.service.smssendlogmanage.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.com.ashen.dal.dataobject.SmsReport;
import org.com.ashen.service.service.smssendlogmanage.sms.aliy.ReportResponseAliy;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.framework.dto.CustomSmsIdAndMobile;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.framework.dto.CustomSmsIdAndMobileAndContent;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.framework.dto.PersonalityParams;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.http.v1.dto.request.*;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.http.v1.dto.response.BalanceResponse;
import org.com.ashen.service.service.smssendlogmanage.sms.inter.http.v1.dto.response.SmsResponse;
import org.com.ashen.service.service.smssendlogmanage.sms.manage.dos.SmsReportDO;
import org.com.ashen.service.service.smssendlogmanage.sms.util.AES;
import org.com.ashen.service.service.smssendlogmanage.sms.util.GZIPUtils;
import org.com.ashen.service.service.smssendlogmanage.sms.util.JsonHelper;
import org.com.ashen.service.service.smssendlogmanage.sms.util.http.*;

import java.text.SimpleDateFormat;
import java.util.*;

public class AliyunSmsUtil {

	
//	public static void main(String[] args) throws Exception {
//        String accessKeyId = "testId";
//        String accessSecret = "testSecret";
//        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//        df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
//        java.util.Map<String, String> paras = new java.util.HashMap<String, String>();
//        // 1. 系统参数
//        paras.put("SignatureMethod", "HMAC-SHA1");
//        paras.put("SignatureNonce", java.util.UUID.randomUUID().toString());
//        paras.put("AccessKeyId", accessKeyId);
//        paras.put("SignatureVersion", "1.0");
//        paras.put("Timestamp", df.format(new java.util.Date()));
//        paras.put("Format", "XML");
//        // 2. 业务API参数
//        paras.put("Action", "SendSms");
//        paras.put("Version", "2017-05-25");
//        paras.put("RegionId", "cn-hangzhou");
//        paras.put("PhoneNumbers", "15300000001");
//        paras.put("SignName", "阿里云短信测试专用");
//        paras.put("TemplateParam", "{\"customer\":\"test\"}");
//        paras.put("TemplateCode", "SMS_71390007");
//        paras.put("OutId", "123");
//        // 3. 去除签名关键字Key
//        if (paras.containsKey("Signature"))
//            paras.remove("Signature");
//        // 4. 参数KEY排序
//        java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<String, String>();
//        sortParas.putAll(paras);
//        // 5. 构造待签名的字符串
//        java.util.Iterator<String> it = sortParas.keySet().iterator();
//        StringBuilder sortQueryStringTmp = new StringBuilder();
//        while (it.hasNext()) {
//            String key = it.next();
//            sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=").append(specialUrlEncode(paras.get(key)));
//        }
//        String sortedQueryString = sortQueryStringTmp.substring(1);// 去除第一个多余的&符号
//        StringBuilder stringToSign = new StringBuilder();
//        stringToSign.append("GET").append("&");
//        stringToSign.append(specialUrlEncode("/")).append("&");
//        stringToSign.append(specialUrlEncode(sortedQueryString));
//        String sign = sign(accessSecret + "&", stringToSign.toString());
//        // 6. 签名最后也要做特殊URL编码
//        String signature = specialUrlEncode(sign);
//        System.out.println(paras.get("SignatureNonce"));
//        System.out.println("\r\n=========\r\n");
//        System.out.println(paras.get("Timestamp"));
//        System.out.println("\r\n=========\r\n");
//        System.out.println(sortedQueryString);
//        System.out.println("\r\n=========\r\n");
//        System.out.println(stringToSign.toString());
//        System.out.println("\r\n=========\r\n");
//        System.out.println(sign);
//        System.out.println("\r\n=========\r\n");
//        System.out.println(signature);
//        System.out.println("\r\n=========\r\n");
//        // 最终打印出合法GET请求的URL
//        System.out.println("http://dysmsapi.aliyuncs.com/?Signature=" + signature + sortQueryStringTmp);
//    }
//    public static String specialUrlEncode(String value) throws Exception {
//        return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
//    }
//    public static String sign(String accessSecret, String stringToSign) throws Exception {
//        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
//        mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
//        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
//        return new sun.misc.BASE64Encoder().encode(signData);
//    }
	
//	阿申公司
//	private static String appId = "LTAI4G25WBiKfb3F5ZFr1KwC";// 请联系销售，或者在页面中 获取 appId
//	private static String secretKey = "iPRpIRIo0yM4EXhDiQhTobzf7jFD5g";// 请联系销售，或者在页面中 获取 密钥
//	上卧
	private static String appId = "LTAI4GB5s3ZvqaJNQaEy34Tw";// 请联系销售，或者在页面中 获取 appId
	private static String secretKey = "7mlCi9SlDkNwlERfh4Z87R2XBOHfMf";// 请联系销售，或者在页面中 获取 密钥
	private static String host = "http://bjksmtn.b2m.cn";// 请联系销售获取 接口地址
	private static String algorithm = "AES/ECB/PKCS5Padding";// 加密算法
	private static String encode = "UTF-8"; // 编码
	private static boolean isGzip = true; // 是否压缩
	
	
	/**
	 * 获取余额
	 * 
	 *  是否压缩
	 */
	public static void getBalance() {
		BalanceRequest pamars = new BalanceRequest();
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/getBalance", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			BalanceResponse response = JsonHelper.fromJson(BalanceResponse.class, result.getResult());
			if (response != null) {
				System.out.println("result data : " + response.getBalance());
			}
		}
	}
 
	/**
	 * 获取状态报告
	 * 
	 *  是否压缩
	 */
	public static List<SmsReport> getReport(String mobile,String senddate,String smsid) {
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", appId, secretKey);
		IAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();
		request.setMethod(MethodType.POST);
		request.setDomain("dysmsapi.aliyuncs.com");
		request.setVersion("2017-05-25");
		request.setAction("QuerySendDetails");
		request.putQueryParameter("PageSize", "1");
		request.putQueryParameter("CurrentPage", "1");
		request.putQueryParameter("PhoneNumber", mobile);
		if(senddate.equals("")){
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			senddate = sdf.format(date);
		}
		request.putQueryParameter("SendDate", senddate);
		request.putQueryParameter("BizId", smsid);
		try {
			CommonResponse response = client.getCommonResponse(request);
			JSONObject jsonObject = JSON.parseObject(response.getData());
			JSONObject jsonObject1 = jsonObject.getJSONObject("SmsSendDetailDTOs");
			JSONArray jsonArray = jsonObject1.getJSONArray("SmsSendDetailDTO");
			ReportResponseAliy reportResponseAliy = JSON.parseObject(JSON.toJSONString(jsonArray.get(0)),ReportResponseAliy.class);
			List<SmsReport> smsReports = new ArrayList<>();
			smsReports.add(SmsReportDO.aliyReportResponseToSmsReport(reportResponseAliy, smsid));
			return smsReports;
		}catch (Exception e){
			return new ArrayList<>();
		}

	}


	/**
	 * 发送单条短信
	 * 
	 *  是否压缩
	 */
	public static String setSingleSms( String content, String customSmsId, String extendCode, String mobile) {
		
		 DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", appId, secretKey);
	        IAcsClient client = new DefaultAcsClient(profile);
	        CommonRequest request = new CommonRequest();
	        request.setMethod(MethodType.POST);
	        request.setDomain("dysmsapi.aliyuncs.com");
	        request.setVersion("2017-05-25");
	        request.setAction("SendSms");
	        request.putQueryParameter("RegionId", "cn-hangzhou");
	        request.putQueryParameter("PhoneNumbers", mobile);
	        request.putQueryParameter("SignName", customSmsId);
	        request.putQueryParameter("TemplateCode", extendCode);
	        request.putQueryParameter("TemplateParam", content);

	        System.out.println(JSON.toJSONString(request));

	        try {
	            CommonResponse response = client.getCommonResponse(request);
	            //{"data":"{\"RequestId\":\"003F6DB5-6F0E-5D33-93C3-A5898F8A84CE\",\"Message\":\"OK\",\"BizId\":\"284300429270696651^0\",\"Code\":\"OK\"}","httpResponse":{"encoding":"UTF-8","headers":{"Access-Control-Allow-Origin":"*","x-acs-request-id":"003F6DB5-6F0E-5D33-93C3-A5898F8A84CE","Access-Control-Allow-Methods":"POST, GET, OPTIONS","Connection":"keep-alive","Access-Control-Max-Age":"172800","Content-Length":"110","Access-Control-Allow-Headers":"X-Requested-With, X-Sequence, _aop_secret, _aop_signature","Date":"Wed, 18 Aug 2021 07:11:36 GMT","Content-Type":"application/json;charset=utf-8"},"httpContent":"eyJSZXF1ZXN0SWQiOiIwMDNGNkRCNS02RjBFLTVEMzMtOTNDMy1BNTg5OEY4QTg0Q0UiLCJNZXNzYWdlIjoiT0siLCJCaXpJZCI6IjI4NDMwMDQyOTI3MDY5NjY1MV4wIiwiQ29kZSI6Ik9LIn0=","httpContentString":"{\"RequestId\":\"003F6DB5-6F0E-5D33-93C3-A5898F8A84CE\",\"Message\":\"OK\",\"BizId\":\"284300429270696651^0\",\"Code\":\"OK\"}","httpContentType":"JSON","status":200,"success":true,"url":"http://dysmsapi.aliyuncs.com/"},"httpStatus":200}
				System.out.println(JSON.toJSONString(response));
	            JSONObject jsonObject = JSON.parseObject(response.getData());
	            if ("OK".equals(jsonObject.getString("Code"))) {
	    			return jsonObject.getString("BizId");
	    		}
	            return "";
	        } catch (ServerException e) {
	            e.printStackTrace();
	            return "";
	        } catch (ClientException e) {
	            e.printStackTrace();
	            return "";
	        }
	
	}

	/**
	 * 发送批次短信
	 * 
	 *  是否压缩
	 */
	public static void setBatchOnlySms(String content, String extendCode, String[] mobiles) {
		SmsBatchOnlyRequest pamars = new SmsBatchOnlyRequest();
		pamars.setMobiles(mobiles);
		pamars.setExtendedCode(extendCode);
		pamars.setContent(content);
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendBatchOnlySMS", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			SmsResponse[] response = JsonHelper.fromJson(SmsResponse[].class, result.getResult());
			if (response != null) {
				for (SmsResponse d : response) {
					System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
				}
			}
		}
	}

	/**
	 * 发送批次短信
	 * 
	 *  是否压缩
	 */
	public static void setBatchSms(String content, String extendCode, CustomSmsIdAndMobile[] customSmsIdAndMobiles) {
		SmsBatchRequest pamars = new SmsBatchRequest();
		pamars.setSmses(customSmsIdAndMobiles);
		pamars.setExtendedCode(extendCode);
		pamars.setContent(content);
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendBatchSMS", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			SmsResponse[] response = JsonHelper.fromJson(SmsResponse[].class, result.getResult());
			if (response != null) {
				for (SmsResponse d : response) {
					System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
				}
			}
		}
	}

	/**
	 * 发送个性短信
	 * 
	 *  是否压缩
	 */
	public static void setPersonalitySms(String extendCode, CustomSmsIdAndMobileAndContent[] customSmsIdAndMobileAndContents) {
		SmsPersonalityRequest pamars = new SmsPersonalityRequest();
		pamars.setSmses(customSmsIdAndMobileAndContents);
		pamars.setExtendedCode(extendCode);
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendPersonalitySMS", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			SmsResponse[] response = JsonHelper.fromJson(SmsResponse[].class, result.getResult());
			if (response != null) {
				for (SmsResponse d : response) {
					System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
				}
			}
		}
	}

	/**
	 * 发送个性短信
	 * 
	 *  是否压缩
	 */
	public static void setPersonalityAllSms( PersonalityParams[] customSmsIdAndMobileAndContents) {
		SmsPersonalityAllRequest pamars = new SmsPersonalityAllRequest();
		pamars.setSmses(customSmsIdAndMobileAndContents);
		ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendPersonalityAllSMS", isGzip, encode);
		System.out.println("result code :" + result.getCode());
		if ("SUCCESS".equals(result.getCode())) {
			SmsResponse[] response = JsonHelper.fromJson(SmsResponse[].class, result.getResult());
			if (response != null) {
				for (SmsResponse d : response) {
					System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
				}
			}
		}
	}

	/**
	 * 公共请求方法
	 */
	public static ResultModel request(String appId, String secretKey, String algorithm, Object content, String url, final boolean isGzip, String encode) {
		Map<String, String> headers = new HashMap<String, String>();
		HttpRequest<byte[]> request = null;
		try {
			headers.put("appId", appId);
			headers.put("encode", encode);
			String requestJson = JsonHelper.toJsonString(content);
			System.out.println("result json: " + requestJson);
			byte[] bytes = requestJson.getBytes(encode);
			System.out.println("request data size : " + bytes.length);
			if (isGzip) {
				headers.put("gzip", "on");
				bytes = GZIPUtils.compress(bytes);
				System.out.println("request data size [com]: " + bytes.length);
			}
			byte[] parambytes = AES.encrypt(bytes, secretKey.getBytes(), algorithm);
			System.out.println("request data size [en] : " + parambytes.length);
			HttpRequestParams<byte[]> params = new HttpRequestParams<byte[]>();
			params.setCharSet("UTF-8");
			params.setMethod("POST");
			params.setHeaders(headers);
			params.setParams(parambytes);
			params.setUrl(url);
			if (url.startsWith("https://")) {
				request = new HttpsRequestBytes(params, null);
			} else {
				request = new HttpRequestBytes(params);
			}
		} catch (Exception e) {
			System.out.println("加密异常");
			e.printStackTrace();
		}
		HttpClient client = new HttpClient();
		String code = null;
		String result = null;
		try {
			HttpResponseBytes res = client.service(request, new HttpResponseBytesPraser());
			if (res == null) {
				System.out.println("请求接口异常");
				return new ResultModel(code, result);
			}
			if (res.getResultCode().equals(HttpResultCode.SUCCESS)) {
				if (res.getHttpCode() == 200) {
					code = res.getHeaders().get("result");
					if (code.equals("SUCCESS")) {
						byte[] data = res.getResult();
						System.out.println("response data size [en and com] : " + data.length);
						data = AES.decrypt(data, secretKey.getBytes(), algorithm);
						if (isGzip) {
							data = GZIPUtils.decompress(data);
						}
						System.out.println("response data size : " + data.length);
						result = new String(data, encode);
						System.out.println("response json: " + result);
					}
				} else {
					System.out.println("请求接口异常,请求码:" + res.getHttpCode());
				}
			} else {
				System.out.println("请求接口网络异常:" + res.getResultCode().getCode());
			}
		} catch (Exception e) {
			System.out.println("解析失败");
			e.printStackTrace();
		}
		ResultModel re = new ResultModel(code, result);
		return re;
	}

	
}
